package com.linkallcloud.core.security;

import java.nio.charset.StandardCharsets;
import java.security.KeyPair;

import com.linkallcloud.core.util.Utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.AsymmetricAlgorithm;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

public class Pwds {
    // private String privateKey;
    private String publicKey;
    private RSA rsa;

    private static Pwds singleton;

    public Pwds() {
        super();
        String seedStr = Utils.getTransactionId();
        KeyPair pair = SecureUtil.generateKeyPair("RSA", 1024, seedStr.getBytes(StandardCharsets.UTF_8));
        this.rsa = new RSA(AsymmetricAlgorithm.RSA_ECB_PKCS1.getValue(), pair.getPrivate(), pair.getPublic());
        // this.privateKey = rsa.getPrivateKeyBase64();
        this.publicKey = rsa.getPublicKeyBase64();
    }

    public static Pwds me() {
        if (singleton == null) {
            synchronized (Pwds.class) {
                if (singleton == null) {
                    singleton = new Pwds();
                }
            }
        }
        return singleton;
    }

    public String pubicKeyEncrypt(String src) {
        byte[] encrypt = rsa.encrypt(StrUtil.bytes(src, CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey);
        return Base64.encode(encrypt);
    }

    public String privateKeyDecrypt(String enc) {
        byte[] encrypt = Base64.decode(enc);
        byte[] decrypt = rsa.decrypt(encrypt, KeyType.PrivateKey);
        return StrUtil.str(decrypt, CharsetUtil.CHARSET_UTF_8);
    }

    public String privateKeyEncrypt(String src) {
        byte[] encrypt = rsa.encrypt(StrUtil.bytes(src, CharsetUtil.CHARSET_UTF_8), KeyType.PrivateKey);
        return Base64.encode(encrypt);
    }

    public String pubicKeyDecrypt(String enc) {
        byte[] encrypt = Base64.decode(enc);
        byte[] decrypt = rsa.decrypt(encrypt, KeyType.PublicKey);
        return StrUtil.str(decrypt, CharsetUtil.CHARSET_UTF_8);
    }

    public String getPublicKey() {
        return publicKey;
    }

    public static void main(String[] args) {
        v1();
        v2();
    }

    public static void v1() {
        String src = "slkdfjlkjslwerow  fwlje=为了见风使舵fd09weurk2";
        System.out.println(src);
        String encrypt = Pwds.me().pubicKeyEncrypt(src);
        System.out.println(encrypt);
        String decrypt = Pwds.me().privateKeyDecrypt(encrypt);
        System.out.println(decrypt);
    }

    public static void v2() {
        String src = "slkdfjlkjslwerow  fwlje=为了见风使舵fd09weurk2";
        System.out.println(src);
        String encrypt = Pwds.me().privateKeyEncrypt(src);
        System.out.println(encrypt);
        String decrypt = Pwds.me().pubicKeyDecrypt(encrypt);
        System.out.println(decrypt);
    }

}
